package com.fw.application.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.AliComm;
import com.fw.common.Builder;
import com.fw.constant.Constant;
import com.fw.core.redis.RedisCache;
import com.fw.enums.AliPayEnum;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.ShopIngShangJiaForm;
import com.fw.system.web.model.vo.*;
import com.fw.system.web.service.*;
import com.fw.utils.JsonUtils;
import com.fw.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 商甲发行表 前端控制器
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@RestController
@Api(tags = "商甲发行相关")
@RequiredArgsConstructor
@RequestMapping("/shangjia")
public class FwShangjiaController implements BaseController {
    private final IFwShangjiaService shangjiaService;
    private final IFwLogsService logsService;
    private final IFwMoneysService moneysService;
    private final IFwTurnoverService turnoverService;
    private final RedisCache redisCache;
    private final AliComm aliComm;
    private final IFwRuleDatasService fwRuleDatasService;
    private final IFwLockStorageService lockStorageService;
    private final IFwWithdrawShangjiaService fwWithdrawShangjiaService;
    private final IFwCurrencyLogService currencyLogService;
    private final IFwUserService userService;
    private final IFwShangjiaCreateLogService createLogService;
    private final IFwShangjiaReleaseLogService releaseLogService;
    private final IFwShangjiaDeleteLogService deleteLogService;
    private final IFwUljoinService uljoinService;


    /**
     * 查看商甲发行总量
     *
     * @return
     */
    @GetMapping("/listShangJiaCount")
    @ApiOperation("shlo:查询商甲发行总量")
    public Result listShangJiaCount() {
        //定义详细规则
        String detailedRules = "1.平台总发行量12亿商甲，消费产出10亿商甲，推广1亿商甲，原始5000万商甲，技术2500万商甲，管理2500万商甲，发行价:1元/商甲\n2.发行机制:按照VIP实际新增数量，每新增一个VIP系统自动发行一商甲，发行出来的商甲是哪个VIP产生的都有明确来源。\n3.每一商甲必须对应一个VIP账户，账户注销或失效此账户商甲销毀。\n4.认购机制:每位消费者均有认购权，每天每账户只能认购1商甲。有商甲产出时所有消费者均可抢购，具体抢购以付款为准。\n5.推广机制:推广既可得到相应推广奖励，分别为10商甲30商甲100商甲1000商甲，送完为止。";
        List<FwShangjia> list = shangjiaService.list();
        ArrayList<ShangjiaVo> shangjiaVos = new ArrayList<>();
        for (FwShangjia fwShangjia : list) {
            ShangjiaVo shangjiaVo = new ShangjiaVo();
            BeanUtil.copyProperties(fwShangjia, shangjiaVo);
            shangjiaVos.add(shangjiaVo);
        }
        ShangjiaCountVo shangjiaCountVo = new ShangjiaCountVo();
        shangjiaCountVo.setShangjiaVos(shangjiaVos);
        shangjiaCountVo.setDetailedRules(detailedRules);

        return success(shangjiaVos);
    }

    /**
     * 认购原始商甲,待输入
     *
     * @return
     */
    @GetMapping("/ReadyShopIngShangJia")
    @ApiOperation("shlo:查询消费商甲现价")
    public Result ReadyShopIngShangJia() {
        //获取商甲现价
        FwShangjia shangjia = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = shangjia.getPresentPrice();
        return success(presentPrice);
    }

    @ApiOperation("获取原始商甲时的总价")
    @PostMapping("/moneyCount")
    public Result moneyCount(ShopIngShangJiaForm shopIngShangJiaForm) {
        //获取商甲数据
        FwShangjia shangjia = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.ORIGINAL_ID));
        //获取总价格
        BigDecimal presentPrice = shangjia.getPresentPrice();
        //获取总数量
        BigDecimal count = shopIngShangJiaForm.getCount();
        BigDecimal money = shopIngShangJiaForm.getMoney().multiply(count);//总价格,此时的总价格是三位小数
        // money = money.multiply(new BigDecimal("0.01"));//取整后乘以0.01
        return success(money);
    }

    /**
     * 认购原始商甲
     *
     * @param shopIngShangJiaForm
     * @return
     */
    @PostMapping("/ShopIngShangJia")
    @ApiOperation("shlo:认购原始商甲2,传认购商甲数量,支付金额")
    public Result ShopIngShangJia(@RequestBody ShopIngShangJiaForm shopIngShangJiaForm) {

        //获取总数量
        BigDecimal count = shopIngShangJiaForm.getCount();
        BigDecimal money = shopIngShangJiaForm.getMoney().multiply(count);
        String userId = getUser().getId();
        shopIngShangJiaForm.setUserId(userId);
        shopIngShangJiaForm.setMoney(money);
        /**
         * todo 调支付
         */
        try {
            String s = aliComm.appPay(
                    ObjectId.next(),//阿里订单编号
                    money,//金额
                    AliPayEnum.shopIng_shangJia_pay,//回调地址
                    JSON.toJSONString(shopIngShangJiaForm)//附带参数
            );
            return success(s);
        } catch (AlipayApiException e) {
            return new Result().fail(-1, "支付失败");
        }

        /*//获取当前登陆者信息
        FwUser user = getUser();

        //获取原始商甲剩余额度
        FwShangjia shangjia = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.ORIGINAL_ID));
        BigDecimal shopIssue = shangjia.getShopIssue();
        int i = shopIssue.compareTo(shangJiaCount);
        if (i < 0) {
            return new Result().fail(-1, "原始商甲剩余额度不足,不可认购");
        }
        //发放商甲
        //减少原始商甲额度
        BigDecimal multiply = shangjia.getShopIssue().multiply(shangJiaCount);
        shangjia.setShopIssue(multiply);
        shangjiaService.updateById(shangjia);
        //给用户增加商甲
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, user.getId()));
        BigDecimal shangJia = moneys.getShangJia();
        BigDecimal add = shangJia.add(shangJiaCount);
        moneys.setShangJia(add);
        moneysService.updateById(moneys);
        //新增商甲收入日志
        logsService.saveLogs(user.getId(), user.getId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "认购商甲", shangJiaCount.toString());
        //新增支付宝支出日志
        logsService.saveLogs(user.getId(), user.getId(), LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(), "认购商甲", money.toString());
*/
    }

    /**
     * 查看恒定增长条件列表
     *
     * @return
     */
    @GetMapping("/listTurnover")
    @ApiOperation("shlo:查看恒定增长条件列表")
    public Result listTurnover() {
        List<FwTurnover> list = turnoverService.list();
        ArrayList<TurnoverVo> turnoverVos = new ArrayList<>();
        for (FwTurnover fwTurnover : list) {
            TurnoverVo turnoverVo = new TurnoverVo();
            BeanUtil.copyProperties(fwTurnover, turnoverVo);
            turnoverVos.add(turnoverVo);
        }
        return success(turnoverVos);
    }

    /**
     * 查看商甲产出
     */
    @GetMapping("/findOutput")
    @ApiOperation("shlo:查看商甲产出")
    public Result<OutputVo> findOutput() {
        String out_put = redisCache.getCacheObject("out_put");
        OutputVo outputVo = JsonUtils.jsonToPojo(out_put, OutputVo.class);
        return success(outputVo);
    }

    /**
     * 查看商甲存储
     */
    @GetMapping("/findStorage")
    @ApiOperation("shlo:查看商甲存储")
    public Result<StorageVo> findStorage() {
        /*String storage = redisCache.getCacheObject("storage");
        StorageVo storageVo = JsonUtils.jsonToPojo(storage, StorageVo.class);*/
        StorageVo storageVo = new StorageVo();
        String id = getUser().getId();
        List<FwMoneys> list = moneysService.list(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, id));
        double disapperUserAll = list.stream().mapToDouble(o -> o.getDisappear().doubleValue()).sum();
        if (CollectionUtils.isNotEmpty(list)) {
            storageVo.setMoneyCount(list.get(0).getDisappear());
        } else {
            storageVo.setMoneyCount(new BigDecimal(0));
        }
        List<FwShangjia> consumList = shangjiaService.list().stream().filter(o -> o.getId().equals(Constant.ShangJia.CONSUME_ID)).collect(Collectors.toList());
        FwShangjia consum = consumList.get(0);
        storageVo.setPresentPrice(consum.getPresentPrice());
        //锁仓商甲数
        List<FwLockStorage> lockStorages = lockStorageService.list(Wrappers.<FwLockStorage>lambdaQuery().eq(FwLockStorage::getUserId, id));
        BigDecimal lockShangJiaAll = new BigDecimal(0);
        for (FwLockStorage item : lockStorages) {
            lockShangJiaAll = lockShangJiaAll.add(item.getLockCount().add(item.getManLockCount().add(item.getTecLockCount())));
        }
        storageVo.setLockCount(lockShangJiaAll);
        double sumShangJia = list.stream().mapToDouble(o -> o.getShangJia().doubleValue()).sum();
        if (CollectionUtils.isNotEmpty(list)) {
            storageVo.setNowCount(list.get(0).getShangJia());
        } else {
            storageVo.setNowCount(new BigDecimal(0));
        }
        storageVo.setHoldCount(lockShangJiaAll.add(new BigDecimal(sumShangJia)).intValue());
        //分红
        List<FwLogs> bonusDetail = logsService.getBonusDetail(id);
        double sumBonus = null != bonusDetail && bonusDetail.size() > 0 ? logsService.getBonusDetail(id).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum() : 0;
        storageVo.setSystemCount(NumberUtil.add(sumBonus));
        return success(storageVo);
    }

    /**
     * 查看商甲产出
     */
    @GetMapping("/findShangJiaOutput")
    @ApiOperation("shlo:新查看商甲产出")
    public Result<Map<String, Object>> findShangJiaOutput() {
        HashMap<String, Object> data = new HashMap<>();
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        //todo 一下统计后期注意替换为sql执行
        String id = null;


        int i = createLogService.sumAllCreateShangJia();
        BigDecimal sum = new BigDecimal(i);


        int year = createLogService.sumYearCreateShangJia();
        BigDecimal sumYear = new BigDecimal(year);

        Integer yueDetail = createLogService.yueDetail();
        if (yueDetail==null){
            yueDetail = 0;
        }
        BigDecimal sumMonth = new BigDecimal(yueDetail);

        BigDecimal sumDay = new BigDecimal("0");
        for (FwShangjiaCreateLog createLog : createLogService.dayDetail()) {
            sumDay = sumDay.add(createLog.getLogCount());
        }
        //double sumDisappear = logsService.getDisappearTotal(null).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum();
        //肖证总额统计
        BigDecimal sumDisappear = currencyLogService.getById("303204408").getLogCount();
        BigDecimal presentPrice = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID)).getPresentPrice();
        data.put("sum", sum);
        data.put("sumYear", sumYear);
        data.put("sumMonth", sumMonth);
        data.put("sumDay", sumDay);
        data.put("sumDisappear", sumDisappear);
        data.put("presentPrice", presentPrice);
        FwTurnover serviceOne = turnoverService.getOne(Wrappers.<FwTurnover>lambdaQuery()
                .le(FwTurnover::getMoney, presentPrice)
                .gt(FwTurnover::getEndMoney, presentPrice));
        if(ObjectUtil.isEmpty(serviceOne)){
            data.put("increase", "50万 涨1分");
        }else{
            BigDecimal count = serviceOne.getConsumptionQuota().divide(new BigDecimal(10000), 0, BigDecimal.ROUND_DOWN);
            data.put("increase", count.toString()+"万 涨1分");
        }
        return success(data);
    }

    /**
     * 查看商甲年产出明细
     */
    @GetMapping("/findShangJiaYearOutput/{pageNum}/{pageSize}")
    @ApiOperation("shlo:新查看商甲今年产出")
    public Result<PageInfo<ShangJiaLogUserVo>> getShangJiaYearTotal(@PathVariable Integer pageNum,
                                                                    @PathVariable Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        List<FwShangjiaCreateLog> v =createLogService.createAndReleaseYear();
        List<ShangJiaLogUserVo> vos =v.parallelStream().map(item -> {
            ShangJiaLogUserVo vo = Builder.of(ShangJiaLogUserVo::new).build();
            vo.setBuiId(item.getUserId());
            vo.setCreateTime(item.getCreateTime());
            vo.setFormInfo(item.getLogCount().toString());
            String userName = userService.getById(vo.getBuiId()).getUserName();
            vo.setUserName(userName);
            vo.setPhone(item.getPhone());
            return vo;
        }).collect(Collectors.toList());
        vos.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
        PageInfo<ShangJiaLogUserVo> spuPageInfo = new PageInfo<>(vos);
        return success(spuPageInfo);
    }

    /**
     * 查看商甲月产出明细
     */
    @GetMapping("/findShangJiaMonthOutput/{pageNum}/{pageSize}")
    @ApiOperation("shlo:新查看商甲这个月产出")
    public Result<PageInfo<ShangJiaLogUserVo>> getShangJiaMonthTotal(@PathVariable Integer pageNum,
                                                                     @PathVariable Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        List<FwShangjiaCreateLog> v =createLogService.createAndReleaseMonth();
        List<ShangJiaLogUserVo> vos = v.parallelStream().map(item -> {
            ShangJiaLogUserVo vo = Builder.of(ShangJiaLogUserVo::new).build();
            vo.setBuiId(item.getUserId());
            vo.setFormInfo(item.getLogCount().toString());
            String userName = userService.getById(vo.getBuiId()).getUserName();
            vo.setUserName(userName);
            vo.setCreateTime(item.getCreateTime());
            vo.setPhone(item.getPhone());
            return vo;
        }).collect(Collectors.toList());
        vos.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
        PageInfo<ShangJiaLogUserVo> spuPageInfo = new PageInfo<>(vos);
        spuPageInfo.setTotal(vos.size());
        return success(spuPageInfo);
    }

    /**
     * 查看商甲日产出明细
     */
    @GetMapping("/findShangJiaDayOutput/{pageNum}/{pageSize}")
    @ApiOperation("shlo:新查看商甲今日产出")
    public Result<PageInfo<ShangJiaLogUserVo>> getShangJiaDayTotal(@PathVariable Integer pageNum,
                                                                   @PathVariable Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        List<FwShangjiaCreateLog> v =createLogService.createAndReleaseDay();
        List<ShangJiaLogUserVo> vos =v.parallelStream().map(item -> {
            ShangJiaLogUserVo vo = Builder.of(ShangJiaLogUserVo::new).build();
            vo.setBuiId(item.getUserId());
            vo.setFormInfo(item.getLogCount().toString());
            String userName = userService.getById(vo.getBuiId()).getUserName();
            vo.setUserName(userName);
            vo.setCreateTime(item.getCreateTime());
            vo.setPhone(item.getPhone());
            return vo;
        }).collect(Collectors.toList());
        vos.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
        PageInfo<ShangJiaLogUserVo> spuPageInfo = new PageInfo<>(vos);
        return success(spuPageInfo);
    }

    /**
     * 查看线上销证产出明细,日期格式20210716
     */
    @GetMapping({"/getDisappearUpDetail/{pageNum}/{pageSize}/{createTime}", "/getDisappearUpDetail/{pageNum}/{pageSize}"})
    @ApiOperation("shlo:查看线上销证产出明细")
    public Result<PageInfo<Map>> getDisappearUpDetail(@PathVariable Integer pageNum,
                                                      @PathVariable Integer pageSize, @PathVariable(required = false) String createTime) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map> disappearDetail = null;
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip用户查看线上销证产出明细");
        }
        //String id = getUser().getId();
        String id = null;
        //String aliPhone = getUser().getAliPhone();
        if (StringUtils.isEmpty(createTime)) {
            disappearDetail = logsService.getDisappearUpTotal(id);
        } else {
            disappearDetail = logsService.getDisappearUpDetail(id, createTime);
            disappearDetail.stream().forEach(o -> o.put("phone", "*******" + (StringUtils.isNotNull(o.get("phone")) ? o.get("phone").toString().substring(7) : "XXXX")));
        }
        //disappearDetail.stream().forEach(o->o.put("phone","*******"+aliPhone.substring(7)));
        PageInfo<Map> spuPageInfo = new PageInfo<>(disappearDetail);
        return success(spuPageInfo);

    }

    /**
     * 查看线下销证产出明细,日期格式20210716
     */
    @GetMapping({"/getDisappearDownDetail/{pageNum}/{pageSize}/{createTime}", "/getDisappearDownDetail/{pageNum}/{pageSize}"})
    @ApiOperation("shlo:查看线下销证产出明细")
    public Result<PageInfo<Map>> getDisappearDownDetail(@PathVariable Integer pageNum,
                                                        @PathVariable Integer pageSize, @PathVariable(required = false) String createTime) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map> disappearDetail = null;
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip用户查看线下销证产出明细");
        }
        //String id = getUser().getId();
        String id = null;
        //String aliPhone = getUser().getAliPhone();
        if (StringUtils.isEmpty(createTime)) {
            disappearDetail = logsService.getDisappearDownTotal(id);
        } else {
            disappearDetail = logsService.getDisappearDownDetail(id, createTime);
            disappearDetail.stream().forEach(o -> o.put("phone", "*******" + (StringUtils.isNotNull(o.get("phone")) ? o.get("phone").toString().substring(7) : "XXXX")));
        }
        //disappearDetail.stream().forEach(o->o.put("phone","*******"+aliPhone.substring(7)));
        PageInfo<Map> spuPageInfo = new PageInfo<>(disappearDetail);
        return success(spuPageInfo);

    }

    /**
     * 查看线下销证产出明细,日期格式20210716
     */
    @GetMapping("/getBonusDetail")
    @ApiOperation("shlo:查看系统分红明细")
    public Result<Map<String, Object>> getBonusDetail() {
        String id = getUser().getId();
        HashMap<String, Object> map = new HashMap<String, Object>();
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        //累计分红
        double sumBonus = logsService.getBonusDetail(id).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum();
        map.put("sumBonus", sumBonus);
        double lastSumBonus = logsService.getLastBonusDetail(id).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum();
        //TODO 此处 需要骚操作一下，避免 10月分红后 放开即可
        double div = NumberUtil.div(lastSumBonus, 3,4);
        map.put("lastSumBonus", lastSumBonus - div);
        //获取分红比例
        FwRuleDatas datas = fwRuleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.BONUS));
        //获取分红权重
        List<FwLockStorage> listLock = lockStorageService.list(Wrappers.<FwLockStorage>lambdaQuery().eq(FwLockStorage::getUserId, id).and(o -> o.eq(FwLockStorage::getLockCount, new BigDecimal(1000.000).setScale(3)).or().eq(FwLockStorage::getTecLockCount, new BigDecimal(1000.000).setScale(3)).or().eq(FwLockStorage::getManLockCount, new BigDecimal(1000.000).setScale(3))));
        map.put("bonusWeight", listLock.size() + "份/1000商甲");
        //计算下次分红金额
        //初始化锁仓的商甲数量
        BigDecimal countJia = new BigDecimal("0");
        //遍历用户锁仓数据
        countJia = new BigDecimal(lockStorageService.list().stream().mapToDouble(o -> o.getLockCount().doubleValue()).sum());
        //获取锁仓的倍数
        BigDecimal count = countJia.divide(new BigDecimal(1000), 0, BigDecimal.ROUND_UP);
        //获取平台发放消证的所有数据
        List<FwLogs> list = logsService.list(Wrappers.<FwLogs>lambdaQuery()
                .eq(FwLogs::getIsType, LogsTypeEnum.MONEY_INCOME)
                .eq(FwLogs::getModelName, LogsModelEnum.DISAPPEAR_MODEL));
        //初始化发放消证总量
        BigDecimal countDisappear = new BigDecimal("0");
        //遍历平台发放消证的所有数据
        countDisappear = new BigDecimal(list.stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum());
        //嵌入公式    消证总量 / 锁仓的商甲为一个单位
        BigDecimal money = new BigDecimal(0);
        if (count.compareTo(new BigDecimal(0)) > 0 && countJia.compareTo(new BigDecimal(0)) > 0) {
            BigDecimal moneyNo = countDisappear.divide(count, 2, BigDecimal.ROUND_UP);
            //计算最终分红
            money = moneyNo.multiply(datas.getRuleCount());
        }

        map.put("nextBonus", money);
        return success(map);

    }

    /**
     * 查看5种类型商甲明细消费1，市场推广2，原始3，技术4，管理5
     */
    @GetMapping("/getShangJiaClassDetail/{pageNum}/{pageSize}/{id}")
    @ApiOperation("shlo:查看5种类型商甲明细消费1，市场推广2，原始3，技术4，管理5")
    public Result<Map<String, Object>> getShangJiaClassDetail(@PathVariable Integer pageNum,
                                                              @PathVariable Integer pageSize, @PathVariable String id) {
        FwShangjia consum = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, id));
        HashMap<String, Object> map = new HashMap<String, Object>();
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        BigDecimal sum = new BigDecimal(0);
        List<FwShangjiaReleaseLog> logs = Lists.newArrayList();
        if ("1".equals(id)) {
            List<FwShangjiaCreateLog> list = createLogService.list();
            for (FwShangjiaCreateLog log : list) {
                sum = sum.add(log.getLogCount());
            }
            PageHelper.startPage(pageNum, pageSize);
            List<FwShangjiaCreateLog> list1 = createLogService.list();
            map.put("total", consum.getShangjiaQuota());
            map.put("surplus", consum.getShopIssue());
            list1.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
            PageInfo<FwShangjiaCreateLog> usePage = new PageInfo<FwShangjiaCreateLog>(list1);
            map.put("useSum", sum);//对应类型商甲已认购、已分配
            map.put("useList", usePage);//明细
            map.put("sumDestory", consum.getDeleteNum());//对应类型商甲销毁量
            return success(map);
        } else {
            if ("2".equals(id)) {
                id = "4";
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                for (FwShangjiaReleaseLog log : logs) {
                    sum = sum.add(log.getLogCount());
                }
                PageHelper.startPage(pageNum, pageSize);
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                map.put("total", consum.getShangjiaQuota());
                map.put("surplus", consum.getShopIssue());
                logs.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
                PageInfo<FwShangjiaReleaseLog> usePage = new PageInfo<>(logs);
                map.put("useSum", sum);//对应类型商甲已认购、已分配
                map.put("useList", usePage);//明细
                map.put("sumDestory", consum.getDeleteNum());//对应类型商甲销毁量
            } else if ("3".equals(id)) {
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                for (FwShangjiaReleaseLog log : logs) {
                    sum = sum.add(log.getLogCount());
                }
                PageHelper.startPage(pageNum, pageSize);
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                map.put("total", consum.getShangjiaQuota());
                map.put("surplus", consum.getShopIssue());
                logs.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
                PageInfo<FwShangjiaReleaseLog> usePage = new PageInfo<>(logs);
                map.put("useSum", sum);//对应类型商甲已认购、已分配
                map.put("useList", usePage);//明细
                map.put("sumDestory", consum.getDeleteNum());//对应类型商甲销毁量
            } else if ("4".equals(id)) {
                id = "1";
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                for (FwShangjiaReleaseLog log : logs) {
                    sum = sum.add(log.getLogCount());
                }
                PageHelper.startPage(pageNum, pageSize);
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                map.put("total", consum.getShangjiaQuota());
                map.put("surplus", consum.getShopIssue());
                logs.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
                PageInfo<FwShangjiaReleaseLog> usePage = new PageInfo<>(logs);
                map.put("useSum", sum);//对应类型商甲已认购、已分配
                map.put("useList", usePage);//明细
                map.put("sumDestory", consum.getDeleteNum());//对应类型商甲销毁量
            } else if ("5".equals(id)) {
                id = "2";
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                for (FwShangjiaReleaseLog log : logs) {
                    sum = sum.add(log.getLogCount());
                }
                PageHelper.startPage(pageNum, pageSize);
                logs = releaseLogService.list(Wrappers.<FwShangjiaReleaseLog>lambdaQuery().eq(FwShangjiaReleaseLog::getLogType, id));
                map.put("total", consum.getShangjiaQuota());
                map.put("surplus", consum.getShopIssue());
                logs.stream().forEach(o -> o.setPhone("*******" + o.getPhone().substring(7)));
                PageInfo<FwShangjiaReleaseLog> usePage = new PageInfo<>(logs);
                map.put("useSum", sum);//对应类型商甲已认购、已分配
                map.put("useList", usePage);//明细
                map.put("sumDestory", consum.getDeleteNum());//对应类型商甲销毁量
            }


        }
       /* deleteLogService.list();
        PageInfo<FwLogs> listPage = new PageInfo<>(listDestory);
        map.put("listDestory", listPage);*/
        return success(map);

    }

    /**
     * 查看销毁商甲统计以及明细
     */
    @GetMapping("/findDestoryShangJiaDetail/{pageNum}/{pageSize}")
    @ApiOperation("shlo:查看销毁商甲统计以及明细")
    public Result<Map<String, Object>> findDestoryShangJiaDetail(@PathVariable Integer pageNum,
                                                                 @PathVariable Integer pageSize) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        String userId = getUser().getId();
        FwUljoin uljoin = uljoinService.getOne(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIsUse, 1).eq(FwUljoin::getUserId, userId));
        if (uljoin==null){
            return new Result().fail(0,"vip以上级别用户查看");
        }
        List<FwShangjia> listShangJia = shangjiaService.list();
        double sum = listShangJia.stream().mapToDouble(o -> Double.parseDouble(o.getShangjiaQuota().toString())).sum();
        double surplus = listShangJia.stream().mapToDouble(o -> Double.parseDouble(o.getShopIssue().toString())).sum();
        map.put("sum", new BigDecimal(sum));//商甲剩余总量
        map.put("surplus", surplus);
        //销毁商甲数量
        double destoryShangJia = listShangJia.stream().mapToDouble(o -> Double.parseDouble(o.getDeleteNum().toString())).sum();
        map.put("destoryShangJia", destoryShangJia);
        map.put("sumOut", sum - surplus);
        PageHelper.startPage(pageNum, pageSize);
        List<FwShangjiaDeleteLog> listDestory = deleteLogService.list();
        listDestory.stream().forEach(o->o.setUserPhone("*******"+o.getUserPhone().substring(7)));
        PageInfo<FwShangjiaDeleteLog> spuPageInfo = new PageInfo<>(listDestory);
        map.put("destoryList", spuPageInfo);
        return success(map);
    }

    //查询自己现有商甲的明细列表
    @GetMapping("/nowSangjiaList")
    @ApiOperation("商甲存储现有明细")
    public Result nowShangjiaList(){


        return null;

    }
}

